package com.sync.hkmjsyncdata.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sync.hkmjsyncdata.pojo.po.AuthInfo;
import com.sync.hkmjsyncdata.service.IAuthInfoService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GYLogin {

    @Value("${gyhlw.host}")
    private String requestHost;
    @Value("${gyhlw.orgId}")
    private String orgId;
    @Value("${gyhlw.czId}")
    private String czId;
    @Value("${gyhlw.password}")
    private String password;


    @Resource
    IAuthInfoService authInfoService;

    @XxlJob("loginGy")
    public void loginGy(){
        XxlJobHelper.log("开始获取认证权限");
        JSONObject params=new JSONObject();
        params.put("orgId",orgId);
        params.put("czId",czId);
        params.put("password",password);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, params.toJSONString());
        Request request = new Request.Builder()
                .url(requestHost+"/api/station/getToken")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            String responseData = response.body().string();
            XxlJobHelper.log("认证权限返回:{}",responseData);
            if (ObjectUtils.isNotEmpty(responseData)) {
                JSONObject result = JSON.parseObject(responseData);
                if(result.getInteger("status")==200){
                    JSONObject data=result.getJSONObject("data");
                    if(ObjectUtils.isNotEmpty(data)){
                        String token=data.getString("token");
                        AuthInfo authInfo=new AuthInfo().setId("1111").setToken(token);
                        authInfoService.saveOrUpdate(authInfo);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }




}
